package com.ease.dao.ibatis.typehandler;

import java.sql.CallableStatement;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;

import org.apache.commons.lang.ClassUtils;

import com.ease.common.util.Detect;
import com.ibatis.sqlmap.engine.type.TypeHandler;

/**
 * 
 * @author nathanleewei
 * 
 */
public class ClassTypeHandler extends Detect implements TypeHandler {

	protected Class<?> getResult(String value) {
		if (notEmpty(value) && !"null".equalsIgnoreCase(value)) {
			try {
				return ClassUtils.getClass(value);
			} catch (ClassNotFoundException e) {
				e.printStackTrace();
			}
		}
		return null;
	}

	public void setParameter(PreparedStatement ps, int i, Object parameter, String jdbcType) throws SQLException {
		Class<?> value = (Class<?>) parameter;
		ps.setString(i, value.getName());
	}

	public Object getResult(ResultSet rs, String columnName) throws SQLException {
		return getResult(rs.getString(columnName));
	}

	public Object getResult(CallableStatement cs, int columnIndex) throws SQLException {
		return getResult(cs.getString(columnIndex));
	}

	public Object getResult(ResultSet rs, int columnIndex) throws SQLException {
		return getResult(rs.getString(columnIndex));
	}

	public Object valueOf(String value) {
		return getResult(value);
	}

	public boolean equals(Object object, String string) {
		if (object == null || string == null) {
			return object == string;
		} else {
			Object castedObject = valueOf(string);
			return object.equals(castedObject);
		}
	}
}
